<template>
	<view>
		<!-- <view class="container"> -->
		<!-- #ifdef H5 -->
		<fui-nav-bar title="搜索" @leftClick="leftClick">
			<fui-icon name="arrowleft"></fui-icon>
		</fui-nav-bar>
		<!-- #endif -->
		<fui-loading :isFixed="true" :isMask="true" v-if="loadingShow"></fui-loading>
		<view v-else>
			<view class="search-container">
				<!-- 搜索框 -->
				<view class="search-container-bar">
					<!-- #ifdef APP-PLUS -->
					<uni-icons class="search-icons" :color="iconColor" size="22" type="mic-filled" @click="speech" />
					<!-- #endif -->
					<!-- :cancelText="keyBoardPopup ? '取消' : '搜索'" -->
					<uni-search-bar ref="searchBar" style="flex:1;" radius="100" v-model="searchText" :focus="focus"
						:placeholder="hotWorld" clearButton="auto" cancelButton="always" @clear="clear"
						@confirm="confirm" @cancel="cancel" />
				</view>
			</view>

			<view class="search-body">
				<!-- 搜索历史 -->
				<view class="word-container" v-if="localSearchList.length">
					<view class="word-container_header">
						<text class="word-container_header-text">搜索历史</text>
						<uni-icons v-if="!localSearchListDel" @click="localSearchListDel = true" class="search-icons"
							style="padding-right: 0;" :color="iconColor" size="18" type="trash"></uni-icons>
						<view v-else class="flex-center flex-row"
							style="font-weight: 500;justify-content: space-between;">
							<text
								style="font-size: 22rpx;color: #666;padding-top:4rpx;padding-bottom:4rpx;padding-right:20rpx;"
								@click="LocalSearchListClear">全部删除</text>
							<text
								style="font-size: 22rpx;color: #c0402b;padding-top:4rpx;padding-bottom:4rpx;padding-left:20rpx;"
								@click="localSearchListDel = false">完成</text>
						</view>
					</view>

					<view class="word-container_body">
						<view class="flex-center flex-row word-container_body-text"
							v-for="(word,index) in localSearchList" :key="index"
							@click="LocalSearchlistItemClick(word,index)">
							<text class="word-display" :key="word">{{word}}</text>
							<uni-icons v-if="localSearchListDel" size="12" type="closeempty" />
						</view>
					</view>
				</view>
				<!-- 搜索发现 -->
				<view class="word-container">
					<view class="word-container_header">
						<view class="flex-center flex-row">
							<text class="word-container_header-text">热门搜索</text>
							<uni-icons v-if="!netHotListIsHide" class="search-icons" :color="iconColor" size="14"
								type="reload" @click="searchHotRefresh"></uni-icons>
						</view>
						<uni-icons class="search-icons" style="padding-right: 0;" :color="iconColor" size="18"
							:type="netHotListIsHide ? 'eye-slash' : 'eye'"
							@click="netHotListIsHide = !netHotListIsHide"></uni-icons>
					</view>

					<unicloud-db ref="udb" #default="{data, loading, error, options}" field="content"
						collection="opendb-search-hot" orderby="create_date desc,count desc" page-data="replace"
						:page-size="10">
						<text v-if="loading && !netHotListIsHide" class="word-container_body-info">正在加载...</text>
						<view v-else class="word-container_body">
							<template v-if="!netHotListIsHide">
								<text v-if="error" class="word-container_body-info">{{error.message}}</text>
								<template v-else>
									<text v-for="(word,index) in data" class="word-container_body-text"
										style="color: red;font-weight: 500;" :key="index"
										@click="search(word.content)">{{word.content}}</text>
								</template>
							</template>
							<view v-else style="flex:1;">
								<text class="word-container_body-info">当前搜索发现已隐藏</text>
							</view>
						</view>
					</unicloud-db>
				</view>
			</view>


			<view class="">
				<!-- 选项卡 -->
				<fui-sticky>
					<fui-tabs :tabs="tabs" :current="current" @change="onChange" center isDot scroll alignLeft
						style="height: 48px !important;">
					</fui-tabs>
				</fui-sticky>
			</view>


			<!-- 搜索联想 -->

			<view class="search-associative" v-if="associativeShow">
				<uni-list>
					<!-- <uni-list-item v-for="(item,index) in associativeList" :key="item._id" :ellipsis="1" :title="item.title" @click="associativeClick(item)" show-extra-icon clickable :extra-icon="{size:18,color:iconColor,type:'search'}">
						</uni-list-item> -->
					<!-- {{associativeList}} -->
					<uni-list-item v-for="(item,index) in associativeList" :key="item._id" :parentId="pageId"
						:title="item?.title" @click="associativeClick(item,searchText)" :ellipsis="1"
						:note="item?.content.slice(0,15)+'...'"
						:thumb="Array.isArray(item[String(classifyImg[current])])?item[String(classifyImg[current])][0]:item[String(classifyImg[current])]"
						thumb-size="lg" show-extra-icon :rightText="getDateDiff(item.publish_date)" clickable
						:extra-icon="{size:18,color:iconColor,type:'search'}">
					</uni-list-item>
				</uni-list>
			</view>



			<!-- 人脉弹窗 -->
			<fui-modal :buttons="[]" width="600" :zIndex="999" @cancel="connectionsShow=false" :maskClosable="true"
				:show="connectionsShow">
				<text class="fui-title">{{connectionsData?.title}}</text>
				<text class="fui-descr">{{connectionsData?.content}}</text>
				<image show-menu-by-longpress="true" @click="bigImg(connectionsData?.connection_img)"
					style="width: 400rpx;border-radius: 20rpx;" :src="connectionsData?.connection_img" mode="widthFix">
				</image>
				<!-- #ifdef APP-PLUS -->
				<view style="display: flex;justify-content: space-between;width: 80%;flex-direction: row;">
					<fui-button @click="twocode(connectionsData?.connection_img)" text="识别二维码" width="200rpx"
						height="72rpx" :size="28" radius="36rpx" background="#F1F4FA" color="#000" erWidth="0"
						:margin="['24rpx','0','24rpx']">
					</fui-button>
					<fui-button style="margin-left: 50rpx;" @click="saveCode(connectionsData?.connection_img)"
						text="保存二维码" width="200rpx" height="72rpx" :size="28" radius="36rpx" background="#465CFF"
						color="#fff" borderWidth="0" :margin="['24rpx','0','24rpx']">
					</fui-button>
				</view>
				<!-- #endif -->
				<!-- #ifdef H5 -->
				<fui-button style="margin-left: 50rpx;" @click="saveCode(connectionsData?.connection_img)"
					text="保存二维码" width="200rpx" height="72rpx" :size="28" radius="36rpx" background="#465CFF"
					color="#fff" borderWidth="0" :margin="['24rpx','0','24rpx']">
				</fui-button>
				<!-- #endif -->
			</fui-modal>

			<uni-load-more :status="status" />
		</view>
		<!-- </view> -->
	</view>
</template>

<script>
	/**
	 * 云端一体搜索模板
	 * @description uniCloud云端一体搜索模板，自带下拉候选、历史搜索、热搜。无需再开发服务器代码
	 */
	import { getDateDiff, parseCode } from "@/utils/index.js"
	const searchLogDbName = 'opendb-search-log'; // 搜索记录数据库
	const mallGoodsDbName = 'qc-news-articles'; // 文章数据库
	const associativeSearchField = 'title'; // 联想时，搜索框值检索数据库字段名
	const localSearchListKey = '__local_search_history'; //	本地历史存储字段名

	// 数组去重
	const arrUnique = arr => {
		for (let i = arr.length - 1; i >= 0; i--) {
			const curIndex = arr.indexOf(arr[i]);
			const lastIndex = arr.lastIndexOf(arr[i])
			curIndex != lastIndex && arr.splice(lastIndex, 1)
		}
		return arr
	} // 节流
	// 防抖
	function debounce(fn, interval, isFirstAutoRun) {
		/**
		 * 
		 * @param {要执行的函数} fn 
		 * @param {在操作多长时间后可再执行，第一次立即执行} interval 
		 */
		var _self = fn;
		var timer = null;
		var first = true;

		if (isFirstAutoRun) {
			_self();
		}

		return function() {
			var args = arguments;
			var _me = this;
			if (first) {
				first = false;
				_self.apply(_me, args);
			}

			if (timer) {
				clearTimeout(timer)
				// return false;
			}

			timer = setTimeout(function() {
				clearTimeout(timer);
				timer = null;
				_self.apply(_me, args);
			}, interval || 200);
		}
	}

	export default {
		data() {
			return {
				loadingShow: true,
				total: 0, //数据总数
				page: { //分页
					pageSize: 10,
					pageNum: 1
				},
				status: 'more',
				current: 0,
				mallGoodsDbName,
				searchLogDbName,
				statusBarHeight: '0px',
				localSearchList: uni.getStorageSync(localSearchListKey),
				localSearchListDel: false,
				netHotListIsHide: false,
				searchText: '',
				iconColor: '#999999',
				associativeList: [],
				keyBoardPopup: false,
				hotWorld: '请输入关键词', //	搜索热词，如果没有输入即回车，则搜索热词，但是不会加入搜索记录
				focus: true, //	是否自动聚焦
				speechEngine: 'iFly', //	语音识别引擎 iFly 讯飞 baidu 百度
				tabs: [{
					name: '热门文章',
					mallGoodsDbName: 'qc-news-articles',
					publish_type: "0",
					tabIndex:0
				},
				{
					name: 'App',
					mallGoodsDbName: 'qc-news-application',
					publish_type: "1"
				}
				],
				classifyImg: ['articles_img', 'application_logo'],
				connectionsShow: false,
				connectionsData: []
			}
		},
		async created() {
			this.db = uniCloud.database();
			this.searchLogDb = this.db.collection(this.searchLogDbName);
			this.mallGoodsDb = this.db.collection(this.mallGoodsDbName);
			// #ifndef H5
			uni.onKeyboardHeightChange((res) => {
				this.keyBoardPopup = res.height !== 0;
			})
			// #endif

			// this.searchText = getApp().globalData.searchText;
			await this.onTabs({ index: 0 })
			// this.loadingShow = false
		},
		computed: {
			associativeShow() {
				return this.searchText || this.associativeList.length;
			}
		},
		onPullDownRefresh() {
			this.associativeList = []
			this.page.pageSize = 10
			this.page.pageNum = 1
			this.onTabs()
			setTimeout(() => {
				uni.stopPullDownRefresh();
			}, 300);
		},
		// 触底的事件
		onReachBottom() {
			if (this.page.pageNum * this.page.pageSize >= this.total) return
			// 让页码值自增+1
			this.page.pageNum++
			this.status = 'loading'
			this.onTabs()
		},
		onLoad() {
			//#ifdef APP-PLUS
			//#endif
		},
		methods: {
			onChange(e) {
				this.current = e.index
				this.page.pageNum = 1
				this.page.pageSize = 10
				this.associativeList = []
				this.onTabs()
			},
			getDateDiff,
			async onTabs() {
				console.log(this.tabs[this.current]);
				const mallGoodsDb = this.db.collection(this.tabs[this.current].mallGoodsDbName);
				await mallGoodsDb.where({release_status: 1, [associativeSearchField]: new RegExp(this.searchText, 'gi') })
					.count().then(res => {
						this.total = res.result.total
					})
				await mallGoodsDb.where({ release_status: 1, [associativeSearchField]: new RegExp(this.searchText, 'gi') })
					.skip((this.page.pageNum - 1) * this.page.pageSize).limit(this.page
						.pageSize).get().then(res => {
						this.associativeList = this.associativeList.concat(res.result.data)
						if (this.associativeList.length != 0) {
							this.status = 'loading'
						}

						if (res.result.data.length <= 10 || res.result.data == null) {
							this.status = 'noMore'
						} else {
							this.status = 'more'
						}
					})
					this.loadingShow = false
			},
			//预览图片
			bigImg(e) {
				uni.previewImage({
					urls: [e],
					longPressActions: {
						itemList: ['保存图片', '识别二维码'],
						success: function(data) {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
							if (data.tapIndex == 0) {
								plus.nativeUI.closePreviewImage();
								//保存到相册
								uni.saveImageToPhotosAlbum({
									filePath: e,
									success: function() {
										uni.showToast({
											title: '成功保存到系统相册中',
											icon: 'none',
											duration: 2000
										});
									}
								});
							} else {
								parseCode(e)
							}
						},
						fail: function(err) {

						}
					}
				});
			},
			twocode(e) {
				parseCode(e)
			},
			//保存到相册
			saveCode(e) {
				uni.saveImageToPhotosAlbum({
					filePath: e,
					success: function() {
						uni.fui.toast('成功保存到系统相册中')
					}
				});
			},
			//#ifdef H5
			leftClick() {
				uni.switchTab({
					url: "/pages/tabbar/index/index"
				})
			},
			//#endif
			clear(res) {
				this.search("");
			},
			confirm(res) {
				// 键盘确认
				this.search(res.value);
			},
			// 点击取消按钮
			cancel(res) {
				uni.hideKeyboard();
				this.searchText = '';
				this.loadList();
			},
			// 点击搜索
			search(value) {
				if (!value && !this.hotWorld) {
					return;
				}

				if (this.searchText !== value) {
					this.searchText = value
				}
				this.page.pageNum = 1
				this.page.pageSize = 10
				this.associativeList = []
				this.onTabs()
				this.localSearchListManage(value);
				uni.hideKeyboard();
				// this.loadList(this.searchText);
			},
			// 存储搜索记录
			localSearchListManage(word) {
				let list = uni.getStorageSync(localSearchListKey);
				if (list.length) {
					this.localSearchList.unshift(word);
					arrUnique(this.localSearchList);
					if (this.localSearchList.length > 10) {
						this.localSearchList.pop();
					}
				} else {
					this.localSearchList = [word];
				}
				uni.setStorageSync(localSearchListKey, this.localSearchList);
			},

			// 清空历史记录
			LocalSearchListClear() {
				uni.showModal({
					content: "确认清空搜索历史吗",
					confirmText: "删除",
					confirmColor: 'red',
					cancelColor: '#808080',
					success: res => {
						if (res.confirm) {
							this.localSearchListDel = false;
							this.localSearchList = [];
							uni.removeStorageSync(localSearchListKey)
						}
					}
				});
			},
			// 点击历史记录进行搜索
			LocalSearchlistItemClick(word, index) {
				if (this.localSearchListDel) {
					this.localSearchList.splice(index, 1);
					uni.setStorageSync(localSearchListKey, this.localSearchList);
					if (!this.localSearchList.length) {
						this.localSearchListDel = false;
					}
					return;
				}
				this.search(word);
			},
			searchHotRefresh() {
				this.$refs.udb.refresh();
			},
			// 语音搜索
			speech() {
				// #ifdef APP-PLUS
				plus.speech.startRecognize({
					engine: this.speechEngine,
					punctuation: false, // 标点符号 
					timeout: 10000
				}, word => {
					word = word instanceof Array ? word[0] : word;
					this.search(word)
				}, err => {
					console.error("语音识别错误: ", err);
				});
				// #endif
			},
			// 添加搜索记录
			searchLogDbAdd(value) {
				/*
					在此处存搜索记录，如果登录则需要存 user_id，若未登录则存device_id
				 */
				this.getDeviceId().then(device_id => {
					this.searchLogDb.add({
						// user_id: device_id,
						device_id,
						content: value,
						create_date: Date.now()
					})
				})
			},
			// 获取设备id
			getDeviceId() {
				return new Promise((resolve, reject) => {
					const uniId = uni.getStorageSync('uni_id');
					if (!uniId) {
						// #ifdef APP-PLUS
						plus.device.getInfo({
							success: (deviceInfo) => {
								resolve(deviceInfo.uuid)
							},
							fail: () => {
								resolve(uni.getSystemInfoSync().system + '_' + Math.random().toString(
									36).substr(2))
							}
						});
						// #endif
						// #ifndef APP-PLUS
						resolve(uni.getSystemInfoSync().system + '_' + Math.random().toString(36).substr(2))
						// #endif
					} else {
						resolve(uniId)
					}
				})
			},
			// 跳转详情
			associativeClick(item, searchText) {
				const params = { _id: item._id, publish_type: this.tabs[this.current].publish_type }
				if (this.tabs[this.current].publish_type == "2") {
					this.connectionsShow = true
					this.connectionsData = item
				}
				// #ifdef APP-PLUS
				const obj = [{
					url: `/pages/push/wzDetail/wzDetail?item=${JSON.stringify(params)}`
				}, {
					url: `/pages/tabbar/application/appDetail?item=${JSON.stringify(params)}`
				}, {
					url: ``
				}, {
					url: ""
				}, {
					url: `/pages/push/preheat/preheatDetail?item=${JSON.stringify(params)}`
				}, {
					url: `/pages/push/group/groupDetail?item=${JSON.stringify(params)}`
				}, {
					url: `/pages/push/firstOrder/firstOrderDetail?item=${JSON.stringify(params)}`
				}, {
					url: `/pages/push/cheaterDetail/cheaterDetail?item=${JSON.stringify(params)}`
				}, ]
				// #endif
				// #ifdef H5
				const obj = [{
					url: `/pages/push/wzDetail/wzDetail?item=${encodeURI(JSON.stringify(params))}`
				}, {
					url: `/pages/tabbar/application/appDetail?item=${encodeURI(JSON.stringify(params))}`
				}, {
					url: ``
				}, {
					url: ""
				}, {
					url: `/pages/push/preheat/preheatDetail?item=${encodeURI(JSON.stringify(params))}`
				}, {
					url: `/pages/push/group/groupDetail?item=${encodeURI(JSON.stringify(params))}`
				}, {
					url: `/pages/push/firstOrder/firstOrderDetail?item=${encodeURI(JSON.stringify(params))}`
				}, {
					url: `/pages/push/cheaterDetail/cheaterDetail?item=${encodeURI(JSON.stringify(params))}`
				}, ]
				// #endif
				uni.navigateTo({
					url: obj[this.tabs[this.current].publish_type].url
				})
			},
			// 返回主页面
			loadList(text = '') {
				// getApp().globalData.searchText = text;
				uni.switchTab({
					url: "/pages/tabbar/index/index"
				})
				// uni.navigateBack()
			},
			// 反回上一层
			backPage() {
				uni.navigateBack();
			}
		}
	}
</script>

<style>
	/* #ifndef APP-NVUE */
	page {
		height: 100%;
		flex: 1;
	}

	/* #endif */
</style>

<style lang="scss" scoped>
	$search-bar-height: 52px;
	$word-container_header-height: 72rpx;

	uni-scroll-view {
		height: 0px !important;
	}

	.status-bar {
		background-color: #fff;
	}

	.container {
		height: 100%;
		flex: 1;
		background-color: #f7f7f7;
	}

	.search-body {
		background-color: #fff;
		border-bottom-right-radius: 10px;
		border-bottom-left-radius: 10px;
	}

	@mixin uni-flex {

		display: flex;

	}

	@mixin words-display {
		font-size: 26rpx;
		color: #666;
	}

	.flex-center {
		@include uni-flex;
		justify-content: center;
		align-items: center;
	}

	.flex-row {
		@include uni-flex;
		flex-direction: row;
	}

	::v-deep .uni-searchbar {
		padding-left: 0;
	}



	::v-deep .uni-searchbar__box {
		border-width: 0;
	}

	::v-deep .uni-input-placeholder {
		font-size: 28rpx;
	}

	.search-container {
		height: $search-bar-height;
		@include uni-flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		position: relative;
		background-color: #fff;

		@at-root {
			#{&}-bar {
				@include uni-flex;
				flex-direction: row;
				justify-content: center;
				align-items: center;
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
			}
		}
	}

	.search-associative {

		overflow-y: auto;

		// position: absolute;
		// top: $search-bar-height;
		// left: 0;
		// right: 0;
		// bottom: 0;
		background-color: #fff;
		margin-top: 10rpx;
		padding-left: 10rpx;
		padding-right: 10rpx;
	}

	.search-icons {
		padding: 16rpx;
	}

	.word-display {
		@include words-display;
	}

	.word-container {
		padding: 20rpx;

		@at-root {
			#{&}_header {
				@include uni-flex;
				height: $word-container_header-height;
				line-height: $word-container_header-height;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;

				@at-root {
					#{&}-text {
						color: #3e3e3e;
						font-size: 30rpx;
						font-weight: bold;
					}
				}
			}

			#{&}_body {
				@include uni-flex;
				flex-wrap: wrap;
				flex-direction: row;

				@at-root {
					#{&}-text {
						@include uni-flex;
						@include words-display;
						justify-content: center;
						align-items: center;
						background-color: #f6f6f6;
						padding: 10rpx 20rpx;
						margin: 20rpx 30rpx 0 0;
						border-radius: 30rpx;
						/* #ifndef APP-NVUE */
						box-sizing: border-box;
						/* #endif */
						text-align: center;
					}

					#{&}-info {
						/* #ifndef APP-NVUE */
						display: block;
						/* #endif */
						flex: 1;
						text-align: center;
						font-size: 26rpx;
						color: #808080;
						margin-top: 20rpx;
					}
				}
			}
		}
	}
</style>